package com.yi.student.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.konghao.basic.model.Pager;
import org.konghao.poi.util.ExcelUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.yi.service.IRewardAndPubnishService;
import com.yi.service.IStudentService;
import com.yi.student.dto.ExcelDto;
import com.yi.student.export.IExportDao;
import com.yi.student.model.RewardAndPubnish;
import com.yi.student.model.Student;
import com.yi.student.util.WebUtil;


@Controller
@RequestMapping("/stu")
public class StudentController {
	
	private IStudentService studentService ;
	
	private IExportDao exportDao ;
	
	private IRewardAndPubnishService rewardAndPubnishServier ;
	

	public IRewardAndPubnishService getRewardAndPubnishServier() {
		return rewardAndPubnishServier;
	}

	@Inject
	public void setRewardAndPubnishServier(
			IRewardAndPubnishService rewardAndPubnishServier) {
		this.rewardAndPubnishServier = rewardAndPubnishServier;
	}

	public IExportDao getExportDao() {
		return exportDao;
	}
	
	@Inject
	public void setExportDao(IExportDao exportDao) {
		this.exportDao = exportDao;
	}

	public IStudentService getStudentService() {
		return studentService;
	}

	@Inject
	public void setStudentService(IStudentService studentService) {
		this.studentService = studentService;
	}

	@RequestMapping("/login")
	public String login(Model model){
		model.addAttribute("hello", "张三");
		return "login";
	}

	@RequestMapping("/list")
	public String list(Model model){
		Pager<Student> page = studentService.page();
		model.addAttribute("stus", page);
		return "stu/lists";
	}
	
	@RequestMapping(value ="/inport" , method = RequestMethod.GET )
	public String inport(){
		return "stu/inport";
	}
	
	@RequestMapping(value="/inport" , method = RequestMethod.POST)
	public String inportStus(@RequestParam MultipartFile file , Model model){
		String name = file.getOriginalFilename() ;
		String tname = WebUtil.fileName();
		name = tname + name ; 
		try {
			if(name != null && !"".equals(name)){
				String type = name.substring(name.indexOf(".") + 1);
				if(!type.equals("xls") && !"xlsx".equals(type) ){
					model.addAttribute("error", "输入的类型不匹配");
					return "stu/inport";
				}
				String path = WebUtil.getUploadPath() + "/" + name;
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path));
				List<Student> stus = WebUtil.transExcel2Student(path);
				studentService.addStudents(stus);
			}else {
				model.addAttribute("error", "您没有选择文件");
				return "stu/inport";
			}
		} catch (IOException e) {
			/**
			 * 如果发生错误 ，应将上传的文件移动到error 文件夹下 ，手动处理 ，
			 * 或者返回错误信息让用户重新上传 
			 */
			e.printStackTrace();
			model.addAttribute("error", "文件上传出错");
			return "stu/inport" ;
		}
		return "redirect:/stu/list";
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/export")
	public void export(HttpServletResponse response) throws IOException{
		
		List datas  = exportDao.listExportDate() ;
		Map<String , String > pa = new HashMap<String , String >() ;
		pa.put("title", "学生信息");
		pa.put("total", String.valueOf(datas.size()));
		pa.put("time", WebUtil.formatNowDate());
	 
		String filename = "学生信息"; //使用汉字 必须转码 ， 因为http 传输时，会把汉字编码ISO8859-1 字符流 ， 在网页也以ISO88959-1 进行转码 ，所以就会乱码
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition: " , "attachment; filename="+new String(filename.getBytes("GBK") , "ISO8859-1")+".xls");
 		ExcelUtil.getInstance().exportObj2ExcelByTemplate(pa, "D:/Workspaces/MyEclipse8.5/student-web/src/com/yi/student/resource/aaq.xls", response.getOutputStream(), datas, ExcelDto.class, false);
		
	}
	
	@RequestMapping(value="/reward/{sid}" , method= RequestMethod.GET )
	public String gotoRewardPage(@PathVariable String sid ,  Model model){
		model.addAttribute("sid", sid);
		model.addAttribute(new RewardAndPubnish());
		return "stu/reward" ;
	}
	
	@RequestMapping(value="/reward/{sid}", method= RequestMethod.POST )
	public String gotoRewardDB(@Valid RewardAndPubnish pad ,BindingResult result , @PathVariable int sid ,  Model model){
		if(result.hasErrors()){
			return  "stu/reward" ;
		}
		Student s = new Student();
		s.setId(sid);
		pad.setIsReward(1);
		pad.setStu(s);
		rewardAndPubnishServier.addRap(pad);
		return "redirect:/stu/list" ;
	}
	
	
	@RequestMapping(value="/publish/{sid}" , method= RequestMethod.GET )
	public String gotoPublishPage(@PathVariable String sid ,  Model model){
		model.addAttribute("sid", sid);
		model.addAttribute("rewardAndPunish", new RewardAndPubnish());
		return "stu/publish" ;
	}
	
	@RequestMapping(value="/publish/{sid}" , method= RequestMethod.POST )
	public String gotoPublishDB(@Valid RewardAndPubnish pad ,BindingResult result , @PathVariable int sid ,  Model model){
		if(result.hasErrors()){
			return "stu/publish";
		}
		
		Student s = new Student();
		s.setId(sid);
		pad.setIsReward(0);
		pad.setStu(s);
		System.out.println(pad.getSituation());
		rewardAndPubnishServier.addRap(pad);
		return "redirect:/stu/list" ;
	}
	
	@RequestMapping("/show/{id}")
	public String showRdAndRp(@PathVariable int id , Model model){
		
		model.addAttribute("stu", studentService.loadStuById(id));
		model.addAttribute("rd", rewardAndPubnishServier.findRewardStudentById(id));
		model.addAttribute("rp" , rewardAndPubnishServier.findPubnishStudentById(id));	
		return "stu/showRdAndRp";
	}
	
	@RequestMapping("/rewards")
	public String showRd( Model model){
		model.addAttribute("rd", rewardAndPubnishServier.findRewardStudent());
		return "stu/showRewards";
	}
	
	@RequestMapping("/publishs")
	public String showRap(Model model){	
		model.addAttribute("rap", rewardAndPubnishServier.findPubnishStudent());
		return "stu/showPublishs";
	}
	

	@RequestMapping(value="/update/{id}" , method=RequestMethod.GET)
	public String updateSutdent(@PathVariable int id , Model model){	
		Student stu = studentService.loadStuById(id);
		model.addAttribute("student", stu);  
		return "stu/updateStu";
	}
	
	@RequestMapping(value="/update/{id}" , method=RequestMethod.POST)
	public String updateSutdent(@PathVariable int id ,@Valid Student student , BindingResult result){	
		if(result.hasErrors()){
			return "stu/updateStu";
		}
		
		Student stu = studentService.loadStuById(id);
		stu.setKsh(student.getKsh());
		stu.setName(student.getName());
		stu.setSex(student.getSex());
		stu.setStatus(student.getStatus());
		stu.setXh(student.getXh());
		studentService.updateStudent(stu);
		return "redirect:/stu/list";
	}

	
}
